﻿using System.Reflection;
using ApiLib.RCL.Components.AutoTable.Attributes;
using ApiLib.RCL.Components.AutoTable.Models;
using ApiLib.RCL.Utils;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Console = System.Console;

namespace ApiLib.RCL.Components.AutoTable;

public partial class AutoTableDetailComponent<TItem> : ComponentBase
    where TItem : IAutoTable<TItem>, new()
{
    /// <summary>
    /// 实体
    /// </summary>
    [Parameter]
    public TItem Entity { get; set; } = new();

    /// <summary>
    /// 是否编辑
    /// </summary>
    [Parameter]
    public bool IsDisabled { get; set; }

    /// <summary>
    /// 按钮样式
    /// </summary>
    [Parameter]
    public bool IsOutline { get; set; }

    [Parameter] public Func<bool, Task>? OnClose { get; set; } = null;

    [Inject] private SwalService swal { get; set; }
    [Inject] private MessageService message { get; set; }
    
    /// <summary>
    /// 
    /// </summary>
    private TableAttribute _tableAttribute  = new ();

    private readonly Dictionary<ColumnAttribute, PropertyInfo> _fields = new();
    private bool _isAdd => Entity.Id == 0;

    protected override async Task OnInitializedAsync()
    {
        var tableAttribute = Entity.GetTableAttribute();
        if (tableAttribute != null)
        {
            _tableAttribute = tableAttribute;
        }
        var properties = typeof(TItem).GetProperties();
        Console.WriteLine($"获取属性值：{Entity.Serialize()}");
        foreach (var propertyInfo in properties)
        {
            var columnAttribute = propertyInfo.GetCustomAttribute<ColumnAttribute>();
            
            if (_tableAttribute.UseDefaultColumn && columnAttribute==null)
            {
                columnAttribute = new ColumnAttribute();
            }

            if (columnAttribute != null)
            {
                if (_isAdd)
                {
                    if (columnAttribute.ShowOnAdd)
                    {
                        _fields[columnAttribute] = propertyInfo;
                    }
                }
                else
                {
                    if (columnAttribute.ShowOnEdit)
                    {
                        //获取默认值
                        columnAttribute.Value = propertyInfo.GetValue(Entity) ?? "";
                        _fields[columnAttribute] = propertyInfo;
                    }
                }
                if (string.IsNullOrEmpty(columnAttribute.Name))
                {
                    columnAttribute.Name = propertyInfo.Name;
                }
            }
        }

        Console.WriteLine("初始化成功");
    }

    private async Task ToSubmit()
    {
        var item = Entity;
        foreach (var (columnAttribute, propertyInfo) in _fields)
        {
            if (!columnAttribute.Nullable && string.IsNullOrEmpty(columnAttribute.Value?.ToString()))
            {
                await NotifyWarning($"{columnAttribute.Name}不能为空");
                return;
            }
            propertyInfo.SetFieldValue(item, columnAttribute.Value);
        }

        var res = await Entity.OnSaveOrUpdate();
        if (res is { code: 0 })
        {
            await NotifySuccess("保存成功");
            if (OnClose != null)
            {
                await OnClose.Invoke(true);
            }
        }
        else
        {
            await NotifyWarning(res?.msg ?? "保存失败");
        }
    }

    private async Task ToCancel()
    {
        if (OnClose != null)
        {
            await OnClose.Invoke(false);
        }
    }
    
    
    /// <summary>
    /// 警告
    /// </summary>
    /// <param name="content"></param>
    public async Task NotifyWarning(string content)
    {
        if (_tableAttribute.IsSwalNotify)
        {
            await swal.SweetWarning("提示", content);
        }
        else
        {
            await message.MessageWarning(content);
        }
    }
    
    /// <summary>
    /// 成功
    /// </summary>
    /// <param name="content"></param>
    public async Task NotifySuccess(string content)
    {
        if (_tableAttribute.IsSwalNotify)
        {
            await swal.SweetSuccess("成功", content);
        }
        else
        {
            await message.MessageSuccess(content);
        }
    }
}